package com.example.caoben_back.tool;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RequiredArgsConstructor
@Component
@Slf4j
public class Tools {
    @Autowired
    private VectorStore vectorStore;

    @Autowired
    private RestTemplate restTemplate;

    @Tool(description = "用户提到中药材相关信息时检索向量数据库，仅限于系统提示词已知的41种药材")
    public String handleRAG(@ToolParam(description = "用户查询的问题") String prompt) {
        log.debug("用户查询的问题：{}", prompt);
        SearchRequest request = SearchRequest.builder()
                .query(prompt) // 查询
                .topK(3)  // 返回的相似文档数量
                .similarityThreshold(0.6) // 相似度阈值
                //.filterExpression("file_name == '中二知识笔记.pdf'")  // 过滤条件
                .build();
        List<Document> docs = vectorStore.similaritySearch(request);

        if (docs.isEmpty()) { // 补充空列表判断，避免NPE
            log.debug("没有搜索到任何内容");
            return "没有搜索到任何内容";
        }

        // 用StringBuilder拼接所有文档信息
        StringBuilder result = new StringBuilder();
        result.append("检索到以下相关内容：\n\n");
        for (int i = 0; i < docs.size(); i++) {
            Document doc = docs.get(i);
            // 拼接序号、文档ID、相似度得分和内容
            result.append("【文档").append(i + 1).append("】\n")
                    .append("ID：").append(doc.getId()).append("\n")
                    .append("相似度：").append(doc.getScore()).append("\n")
                    .append("内容：").append(doc.getText()).append("\n\n");
        }
        log.debug("检索结果：{}", result);
        return result.toString();
    }
    
    // 使用外部网络搜索服务替代Playwright
    @Tool(description = "通过开放网络搜索服务获取信息")
    public String webSearch(@ToolParam(description = "用户查询的问题") String query) {
        try {
            log.debug("开始使用开放网络搜索服务，关键词：{}", query);
            
            // 创建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("query", query);
            requestBody.put("limit", 10);
            requestBody.put("engines", Arrays.asList("baidu", "bing"));
            
            // 创建HTTP头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 创建HTTP请求
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                "http://10.108.13.254:3002/search", 
                requestEntity, 
                String.class
            );
            
            // 检查响应状态
            if (response.getStatusCode() == HttpStatus.OK) {
                // 解析JSON响应
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(response.getBody());
                
                // 构建返回结果
                StringBuilder result = new StringBuilder();
                result.append("通过网络搜索得到以下结果：\n\n");
                
                for (JsonNode item : rootNode) {
                    String title = item.get("title") != null ? item.get("title").asText() : "未知标题";
                    String url = item.get("url") != null ? item.get("url").asText() : "";
                    String description = item.get("description") != null ? item.get("description").asText() : "";
                    String source = item.get("source") != null ? item.get("source").asText() : "未知来源";
                    String engine = item.get("engine") != null ? item.get("engine").asText() : "未知引擎";
                    
                    result.append("标题：").append(title).append("\n");
                    if (!url.isEmpty()) {
                        result.append("链接：").append(url).append("\n");
                    }
                    if (!description.isEmpty()) {
                        result.append("描述：").append(description).append("\n");
                    }
                    result.append("来源：").append(source).append("\n");
                    result.append("搜索引擎：").append(engine).append("\n\n");
                }

                log.debug("网络搜索结果：{}", result);
                return result.toString();
            } else {
                log.error("网络搜索请求失败，状态码：{}", response.getStatusCode());
                return "网络搜索请求失败，状态码：" + response.getStatusCode();
            }
        } catch (Exception e) {
            log.error("网络搜索出错：", e);
            return "网络搜索过程中出现错误：" + e.getMessage();
        }
    }
}